package com.chao.test.controller;

import cn.hutool.core.date.DateUtil;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.text.DateFormat;
import java.util.Date;
import java.util.Objects;

@RestController
@RequestMapping("/file")
public class FileController {

    private static final String UPLOAD_PATH = "F:\\file\\";

    @PostMapping("/nio/upload")
    public String nioUploadFile(MultipartFile file) {
        if (Objects.isNull(file) || file.isEmpty()) {
            throw new RuntimeException("请选择要上传的文件");
        }
        if (Objects.isNull(file.getOriginalFilename())) {
            throw new RuntimeException("文件名称为空");
        }

        try {
            // 创建文件上传的路径
            String dateStr = DateUtil.date(new Date()).toString("yyyy-MM-dd");
            String path = UPLOAD_PATH.concat(dateStr);
            Path targetPath = Paths.get(path).toAbsolutePath();
            Files.createDirectory(targetPath);

            String filename = file.getOriginalFilename();

            // 构建目标文件的完整路径
            Path destinationPath = targetPath.resolve(filename);

            // 使用NIO异步非阻塞的方式复制文件 覆盖同名文件
            Files.copy(file.getInputStream(), destinationPath, StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return "success";
    }
}
